package mqigdcom.mqigd;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;

import mqigdcom.mqigd.netapi.INetApi;
import mqigdcom.mqigd.netapi.NetApiConst;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;

public class CustomApp extends Application {

    public static CustomApp self;// 应用实例
    public INetApi netApi;// 网络接口的实例
    private List<Activity> activities;
    public SharedPreferences sp;// 本地存储类
    public INetApi tnetApi;// 网络接口的实例
    public static final String DOWNLOAD_PATH = "/data/data/mqigdcom.mqigd/download";
    public static final String appFileName = "MQI.apk";  //版本
    @Override
    public void onCreate() {
        super.onCreate();
        self = this;
        netApi = new Retrofit.Builder()
                .baseUrl(NetApiConst.BASE_URL)
                .client(new OkHttpClient.Builder()
                        .connectTimeout(30000, TimeUnit.MILLISECONDS)
                        .readTimeout(30000, TimeUnit.MILLISECONDS).build())
                .build()
                .create(INetApi.class);
        tnetApi = new Retrofit.Builder()
                .baseUrl("http://172.16.210.205:20041/")
                .client(new OkHttpClient.Builder()
                        .connectTimeout(30000, TimeUnit.MILLISECONDS)
                        .readTimeout(30000, TimeUnit.MILLISECONDS).build())
                .build()
                .create(INetApi.class);
        sp = getSharedPreferences("mqi", Context.MODE_PRIVATE);
    }

    /**
     * 将新的Activity入栈存储
     *
     * @param activity Activity实例
     */
    public void addActivity(Activity activity) {
        if (activity != null) {
            if (this.activities == null) {
                activities = new ArrayList<>();
            }
            activities.add(activity);
        }
    }

    /**
     * 移除已经存在的Activity
     *
     * @param activity Activity实例
     */
    public void removeActivity(Activity activity) {
        if (activity != null && this.activities != null) {
            this.activities.remove(activity);
        }
    }

    /**
     * 移除所有已经存在的Activity
     */
    private void removeAllActivities() {
        if (this.activities != null) {
            for (int i = this.activities.size() - 1; i >= 0; i--) {
                this.activities.remove(i);
            }
        }
    }

    /**
     * 退出应用
     */
    public void exitApp() {
        removeAllActivities();
        System.exit(0);
    }
}
